package com.ruoyi.web.controller.tool;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.utils.http.HttpUtils;
import org.springframework.stereotype.Component;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;

@Component
public class WxQrCode {

    //    @Value("${ma.appid}")
//    private static String APIKEY="wx2218b3d7be9f79c9";//小程序id
//    //    @Value("${ma.secret}")
//    private static String SECRETKEY="b26a8f98d51ed8ee250bdba6877557ef";//小程序密钥

    private static String APIKEY="wx981aee419037975d";//小程序id
    private static String SECRETKEY="feda99fa074435d36478de8f7d37b4af";//小程序密钥

    //    @Value("${file.path.upload}")
//    private String uploadPath;
    private static String accessToken = null;

    //获取AccessToken路径
    private static final String AccessToken_URL = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=APPSECRET";//小程序id
    //获取二维码路径
    private static final String WxCode_URL = "https://api.weixin.qq.com/wxa/getwxacode?access_token=ACCESS_TOKEN";//小程序密钥

    //登录凭证校验。通过 wx.login 接口获得临时登录凭证 code 后传到开发者服务器调用此接口完成登录流程。更多使用方法详见小程序登录。
//    https://api.weixin.qq.com/sns/jscode2session
//    GET https://api.weixin.qq.com/sns/jscode2session?appid=APPID&secret=SECRET&js_code=JSCODE&grant_type=authorization_code

    public static HashMap getOpenId(String JSCODE) {
        HashMap<String, String> dataMap = new HashMap<>();
//        GET https://api.weixin.qq.com/sns/jscode2session?appid=APPID&secret=SECRET&js_code=JSCODE&grant_type=authorization_code
        String getUrl = "https://api.weixin.qq.com/sns/jscode2session?appid=" + APIKEY + "&secret=" + SECRETKEY + "&js_code=" + JSCODE + "&grant_type=authorization_code";
        String result = HttpUtils.sendGet(getUrl);
        JSONObject jsonObject = JSON.parseObject(result);
        String openId = jsonObject.getString("openid");
        String unionId = jsonObject.getString("unionId");
        dataMap.put("openId", openId);
        dataMap.put("unionId", unionId);
        System.out.println("openId" + openId);
        System.out.println("unionId" + unionId);
        return dataMap;
    }
//    public static String getQrCodeUrlByDevice(ODeviceInfo deviceInfo) {
//        String wxPath = "/pages/create/index?deviceType="+deviceInfo.getDeviceTypeId()+"&deviceCode="+deviceInfo.getDeviceCode()+"&deviceTypeName="+deviceInfo.getDeviceTypeName()+"&deviceAddress="+deviceInfo.getDeviceAddress();
//        String qrCodeUrl = "";
//        try {
//            accessToken = WxQrCode.getAccessToken(APIKEY,SECRETKEY);
//            qrCodeUrl = WxQrCode.getminiqrQr(accessToken, RuoYiConfig.getUploadPath(), wxPath);
//        } catch (Exception e) {
//            throw new RuntimeException(e);
//        }
//        return qrCodeUrl;
//    }

//    public static String getQrCodeUrl(SysDept sysDept) {
//        String wxPath = "/pages/create/index?repairDeptTel=" + sysDept.getPhone() + "&repairTel=" + sysDept.getTel() + "&repairPosition=" + sysDept.getAddress();
//        String qrCodeUrl = "";
//        try {
//            accessToken = WxQrCode.getAccessToken(APIKEY,SECRETKEY);
//            qrCodeUrl = WxQrCode.getminiqrQr(accessToken, RuoYiConfig.getUploadPath(), wxPath);
//        } catch (Exception e) {
//            throw new RuntimeException(e);
//        }
//        return qrCodeUrl;
//    }

    /**
     * 用于获取access_token
     * @return  access_token
     * @throws Exception
     */
    public static String getAccessToken(String appid,String secret) throws Exception {
        String requestUrl = AccessToken_URL.replace("APPID",appid).replace("APPSECRET",secret);
        URL url = new URL(requestUrl);
        // 打开和URL之间的连接
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setRequestMethod("POST");
        // 设置通用的请求属性
        connection.setRequestProperty("Content-Type", "application/json");
        connection.setRequestProperty("Connection", "Keep-Alive");
        connection.setUseCaches(false);
        connection.setDoOutput(true);
        connection.setDoInput(true);

        // 得到请求的输出流对象
        DataOutputStream out = new DataOutputStream(connection.getOutputStream());
        out.writeBytes("");
        out.flush();
        out.close();

        // 建立实际的连接
        connection.connect();
        // 定义 BufferedReader输入流来读取URL的响应
        BufferedReader in = null;
        if (requestUrl.contains("nlp")) {
            in = new BufferedReader(new InputStreamReader(connection.getInputStream(), "GBK"));
        }else {
            in = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8"));
        }
        String result = "";
        String getLine;
        while ((getLine = in.readLine()) != null) {
            result += getLine;
        }
        in.close();
        JSONObject jsonObject = JSON.parseObject(result);
        String accesstoken=jsonObject.getString("access_token");
        return accesstoken;
    }


    /*
     * 获取 二维码图片
     *
     */
    public static String getminiqrQr(String accessToken,String uploadPath,String wxPath) {
        String ctxPath = uploadPath;
        String fileName=  System.currentTimeMillis()+".png";
        String bizPath = "files";
        String nowday = new SimpleDateFormat("yyyyMMdd").format(new Date());
        String ppath =ctxPath + File.separator + bizPath + File.separator + nowday;
        File file = new File(ctxPath + File.separator + bizPath + File.separator + nowday);
        if (!file.exists()) {
            file.mkdirs();// 创建文件根目录
        }
        String savePath = file.getPath() + File.separator + fileName;
        String qrCode = bizPath + File.separator + nowday+ File.separator + fileName;
//        if (ppath.contains("\\")) {
//            ppath = ppath.replace("\\", "/");
//        }
        if (qrCode.contains("\\")) {
            qrCode = qrCode.replace("\\", "/");
        }
//        String codeUrl=ppath+"/twoCode.png";
        System.out.print(qrCode);
        System.out.print(savePath);
        try {
            String wxCodeURL = WxCode_URL.replace("ACCESS_TOKEN",accessToken);
            URL url = new URL(wxCodeURL);
            HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
            httpURLConnection.setRequestMethod("POST");// 提交模式
            // conn.setConnectTimeout(10000);//连接超时 单位毫秒
            // conn.setReadTimeout(2000);//读取超时 单位毫秒
            // 发送POST请求必须设置如下两行
            httpURLConnection.setDoOutput(true);
            httpURLConnection.setDoInput(true);
            // 获取URLConnection对象对应的输出流
            PrintWriter printWriter = new PrintWriter(httpURLConnection.getOutputStream());
            // 发送请求参数
            JSONObject paramJson = new JSONObject();
//            paramJson.put("scene", "12345678901");
//            paramJson.put("path", "/pages/create/index?repairDeptTel=1222222&repairTel=4343343&contactsName=姚君豪&contactsPhone=18888888&repairPosition=1楼"); //小程序暂未发布我没有带page参数
            paramJson.put("path",wxPath);
            paramJson.put("width", 430);
//            paramJson.put("is_hyaline", true);
//            paramJson.put("auto_color", true);
            /**
             * line_color生效
             * paramJson.put("auto_color", false);
             * JSONObject lineColor = new JSONObject();
             * lineColor.put("r", 0);
             * lineColor.put("g", 0);
             * lineColor.put("b", 0);
             * paramJson.put("line_color", lineColor);
             * */

            printWriter.write(paramJson.toString());
            // flush输出流的缓冲
            printWriter.flush();
            //开始获取数据
            BufferedInputStream bis = new BufferedInputStream(httpURLConnection.getInputStream());
            OutputStream os = new FileOutputStream(new File(savePath));
            int len;
            byte[] arr = new byte[1024];
            while ((len = bis.read(arr)) != -1) {
                os.write(arr, 0, len);
                os.flush();
            }
            os.close();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {

        }
        return Constants.RESOURCE_PREFIX + "/upload/" + qrCode;
    }

}